import { useState } from 'react';

import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement, incrementAsync } from '../redux/counterSlice';

export default function Counter() {
  const [step, setStep] = useState(1);

  const count = useSelector(state => state.count.value);
  const persons = useSelector(state => state.person.value.length);
  const dispatch = useDispatch();

  const incrementHandler = () => {
    dispatch(increment(step * 1));
  };
  const decrementHandler = () => {
    dispatch(decrement(step * 1));
  };
  const incrementSyncHandler = () => {
    dispatch(incrementAsync({ step: step * 1, delay: 500 }));
  };

  return (
    <>
      <div>
        <h2>
          Counter 组件: {count}，下方组件总人数：{persons}
        </h2>
        step:{' '}
        <input
          type="number"
          value={step}
          step={1}
          onChange={e => setStep(e.target.value)}
        />
        <button onClick={incrementHandler}>增加</button>
        <button onClick={decrementHandler}>减去</button>
        <button onClick={incrementSyncHandler}>异步增加</button>
      </div>
    </>
  );
}
